
//文件上传

import {Interceptor} from "../../core/Interceptor";
import {Ctx} from "../../index";
import {_} from "../../util/UtilTs";
import {Log} from "../../util/Log";

var multer  = require('multer');

export class FileUpload extends Interceptor{

    fieldName = "fieldName";
    dest = "uploads/";
    multerFunc;
    constructor(opts:Partial<FileUpload> = {}) {
        super();
        _.merge(this,opts);
        this.multerFunc = multer(this).single(this.fieldName);
    }

    static create =(opts:Partial<FileUpload>)=> new FileUpload(opts);

    before(ctx:Ctx){
        const { req , res ,next} = ctx;

        this.multerFunc(req,res,function (err) {
            if(err){
                Log.err("文件上传失败",err);
                ctx.setcm(-500,err.message);
                ctx.isEnd = true;
                next();
            }
            else {
                ctx.params.file = req.file;
                next();
            }
        });
    }

}



